package com.ly.aidlpratice.messenger

import android.app.Service
import android.content.Intent
import android.os.*
import android.widget.Toast
import com.ly.aidlpratice.util.logDebug
import java.lang.ref.WeakReference
import kotlin.random.Random


open class MessengerService : Service() {

    private val mTag: String by lazy { this::class.java.simpleName }

    private lateinit var mMessenger: Messenger

    override fun onCreate() {
        super.onCreate()
        logDebug(mTag, "onCreate")
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        logDebug(mTag, "onStartCommand")
        return super.onStartCommand(intent, flags, startId)
    }

    override fun onDestroy() {
        super.onDestroy()
        logDebug(mTag, "onDestroy")
        Process.killProcess(Process.myPid())
    }

    override fun onBind(intent: Intent): IBinder {
        logDebug(mTag, "onBind $intent")
        mMessenger = Messenger(MessengerHandler(this))
        return mMessenger.binder
    }

    override fun onUnbind(intent: Intent?): Boolean {
        logDebug(mTag, "onUnbind ${intent?.toString() ?: ""}")
        return super.onUnbind(intent)
    }

    fun getRandomNumber(): Int {
        logDebug(mTag, "getRandomNumber")
        val random = Random(100000)
        return random.nextInt()
    }

    internal class MessengerHandler(service: MessengerService) : Handler(Looper.getMainLooper()) {

        private val mTag: String by lazy { this::class.java.simpleName }

        private var mService: WeakReference<MessengerService> = WeakReference(service)

        private lateinit var mClientMessenger: Messenger

        override fun handleMessage(msg: Message) {
            super.handleMessage(msg)
            mService.get()?.also {
                when (msg.what) {
                    MSG_WHAT_GET_CLIENT_HANDLER -> {
                        mClientMessenger = msg.replyTo
                        logDebug(mTag, "收到客户端的Messenger，可以发消息给客户端了")
                    }
                    MSG_WHAT_FROM_CLIENT_CLICK -> {
                        Toast.makeText(it, "收到来自MessengerActivity的消息", Toast.LENGTH_LONG).show()
                        if (this::mClientMessenger.isInitialized) {
                            logDebug(mTag, "向客户端发送消息")
                            //用msg.obj传递对象，对象一定要序列化，因为是跨进程
                            val message = Message.obtain()
                            message.arg1 = it.getRandomNumber()
                            message.what = MessengerActivity.ClientHandler.MSG_WHAT_FROM_SERVICE
                            mClientMessenger.send(message)
                        } else {
                            logDebug(mTag, "未收到客户端的Messenger")
                        }
                    }
                }
            }
        }

        companion object {
            const val MSG_WHAT_FROM_CLIENT_CLICK = 0
            const val MSG_WHAT_GET_CLIENT_HANDLER = 1
        }
    }
}